<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Angle Bounce Rotate</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Move mouse left or right on canvas element.</aside>

    <script src="../include/utils.js"></script>
    <script src="./classes/ball.js"></script>
    <script src="./classes/line.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          mouse = utils.captureMouse(canvas),
          ball = new Ball(),
          line = new Line(0, 0, 300, 0),
          gravity = 0.2,
          bounce = -0.6;

      ball.x = 100;
      ball.y = 100;

      line.x = 50;
      line.y = 200;

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        //move line with mouse
        line.rotation = ((canvas.width / 2 - mouse.x) * 0.1) * Math.PI / 180;
        //normal motion code
        ball.vy += gravity;
        ball.x += ball.vx;
        ball.y += ball.vy;
        //get sine and cosine of angle
        var cos = Math.cos(line.rotation),
            sin = Math.sin(line.rotation),
            //get position of ball, relative to line
            x1 = ball.x - line.x,
            y1 = ball.y - line.y,
            //rotate coordinates
            y2 = cos * y1 - sin * x1;
        //perform bounce with rotated values
        if (y2 > -ball.radius) {
          //rotate coordinates
          var x2 = cos * x1 + sin * y1,
              //rotate velocity
              vx1 = cos * ball.vx + sin * ball.vy,
              vy1 = cos * ball.vy - sin * ball.vx;
          y2 = -ball.radius;
          vy1 *= bounce;
          //rotate everything back
          x1 = cos * x2 - sin * y2;
          y1 = cos * y2 + sin * x2;
          ball.vx = cos * vx1 - sin * vy1;
          ball.vy = cos * vy1 + sin * vx1;
          ball.x = line.x + x1;
          ball.y = line.y + y1;
        }
        ball.draw(context);
        line.draw(context);
      }());
    };
    </script>
  </body>
</html>
